package com.thoughtworks.oo.quantity;

public abstract class Quantity<Q extends Quantity, U extends Unit> {
    protected final int amount;
    protected final U unit;
    private final Class<Q> quantityClass;
    private final Class<U> unitClass;

    public Quantity(int amount, U unit, Class<Q> quantityClass, Class<U> unitClass) {
        this.amount = amount;
        this.unit = unit;
        this.quantityClass = quantityClass;
        this.unitClass = unitClass;
    }

    public Q plus(Q another) {
        try {
            return quantityClass.getConstructor(new Class[]{Integer.class, unitClass}).
                    newInstance(getAmountOfBaseUnit() + another.getAmountOfBaseUnit(), unit.getBaseUnit());
        } catch (Exception e) {
            throw new IllegalStateException(e.getMessage());
        }
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;

        Quantity quantity = (Quantity) o;

        return getAmountOfBaseUnit() == quantity.getAmountOfBaseUnit();
    }

    @Override
    public int hashCode() {
        return getAmountOfBaseUnit();
    }

    protected int getAmountOfBaseUnit() {
        return unit.getBaseAmount(amount);
    }


}


